package cn.wwcyc.utils;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class MQTTUtil {

    public static void sendMsg(StringBuilder msg){
        String broker = "tcp://10.76.38.67:1883"; // MQTT服务器地址
        String clientId = "WWCYC"; // 客户端ID
        MemoryPersistence persistence = new MemoryPersistence();
        MqttClient wwClient = null;

        try {
            wwClient = new MqttClient(broker, clientId, persistence);
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setCleanSession(true); // 设置是否清空会话

//            System.out.println("Connecting to broker: " + broker);
            wwClient.connect(connOpts);
//            System.out.println("Connected");
            String topic = "wwcyc/hsl"; // 主题

             // 服务质量等级
            MqttMessage message = new MqttMessage(msg.toString().getBytes());
            message.setQos(0);

            wwClient.publish(topic, message);
//            System.out.println("Message published");

            wwClient.disconnect();
//            System.out.println("Disconnected");

        } catch (MqttException me) {
//            System.out.println("reason " + me.getReasonCode());
//            System.out.println("msg " + me.getMessage());
//            System.out.println("loc " + me.getLocalizedMessage());
//            System.out.println("cause " + me.getCause());
//            System.out.println("excep " + me);
            me.printStackTrace();
        }finally {
            try {
                wwClient.close();
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }

    }
}
